//
//  ViewControllerForPhotoDetail.m
//  世界
//
//  Created by admin on 16/2/17.
//  Copyright © 2016年 admin. All rights reserved.
//

#import "ViewControllerForPhotoDetail.h"
#import "ModelForAll.h"
#import "ModelForForPhotoDetail.h"
#import <UIImageView+WebCache.h>
#import "DataBaseForPhoto.h"
#import "NetworkingHandler.h"

@interface ViewControllerForPhotoDetail ()<UIScrollViewDelegate>

@property (nonatomic, retain) UIScrollView *scrollView;
@property (nonatomic, retain) UIImageView *imgView;
@property (nonatomic, retain) UITextView *textView;
@property (nonatomic, retain) UILabel *lableForTitle;
@property (nonatomic, retain) UILabel *lableForPage;
@property (nonatomic, retain) UIButton *buttonForSave;
@property (nonatomic, retain) NSMutableArray *arrimageView;
@property (nonatomic, retain) UIButton *buttonForCollect;
@property (nonatomic, retain) UIButton *buttonForShare;
@property (nonatomic, assign) BOOL isSelect;
@property (nonatomic, retain) NSMutableArray *arrForModels;
@property (nonatomic, assign) NSInteger path;

@end

@implementation ViewControllerForPhotoDetail

-(void)dealloc
{
    [_id release];
    
    [_scrollView release];
    
    [_imgView release];
    
    [_textView release];
    
    [_lableForTitle release];
    
    [_lableForPage release];
    
    [_buttonForSave release];
    
    [_arrimageView release];
    
    [_buttonForCollect release];
    
    [_arrForModels release];
    
    [_buttonForShare release];
    
    [super dealloc];
}

#pragma mark 视图的生命周期 >>>>>>
#pragma mark 视图加载完成
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.navigationItem.title = @"详情";
    
    UIColor *bg = [UIColor colorWithPatternImage:[UIImage imageNamed:@"图片背景.jpg"]];
    
    self.view.backgroundColor = bg;
    
    
    //解析数据
    [self handleData];
    
    [self creataScorollView];
    
    //添加UITextView
    [self createTextView];
    
    //添加详细内容的标题和页数
    [self createLableForTitleAndPage];
    
    //添加保存按钮
    [self addButtonOfSave];
    
    
    [[DataBaseForPhoto shareDataBaseHandle]open];
    [[DataBaseForPhoto shareDataBaseHandle] createTable];
}




#pragma mark 收到内存警告!!!
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}




#pragma mark 自定义方法 >>>>>>
#pragma mark 解析网路数据
- (void)handleData
{
    //设置访问地址
    NSString *url = [NSString stringWithFormat:@"http://dili.bdatu.com/jiekou/albums/a%d.html", [self.id intValue]];
    
    
    
    [NetworkingHandler netWorkingWithURL:url completeHandle:^(NSURLResponse *response, NSData *data ,id result) {
        
        
        ModelForAll*model = [[ModelForAll alloc] init];
        
        [model setValuesForKeysWithDictionary:result];
        
        [model autorelease];
        
        self.arrForModels = [NSMutableArray array];
        
        for (NSDictionary *dic in model.picture)
        {
            ModelForForPhotoDetail *modelForDetail = [[ModelForForPhotoDetail alloc] init];
            
            [modelForDetail setValuesForKeysWithDictionary:dic];
            
            [self.arrForModels addObject:modelForDetail];
            
            [modelForDetail release];
        }
            
            //设置scroll的内容尺寸
            self.scrollView.contentSize =CGSizeMake(self.scrollView.frame.size.width * self.arrForModels.count, 300);
            
            //初始化用于保存 imageView 的数组, 将图片保存的系统相册的时候从此数组中找出相应的 imageView 的 image;
            self.arrimageView = [NSMutableArray array];
            
            //将图片添加的scrollView上
            for (int i = 0; i < self.arrForModels.count; i++)
            {
                
                ModelForForPhotoDetail *model2 = [self.arrForModels objectAtIndex:i];
                
                self.imgView = [[UIImageView alloc] init];
                
                //解析图片的网址,将图片添加到imageView上
                [self.imgView sd_setImageWithURL:[NSURL URLWithString:model2.url]];
                
                
                //设置imageView的位置及大小 添加的相应的内容视图上
                self.imgView.frame = CGRectMake(self.scrollView.frame.size.width * i, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height);
                
                [self.scrollView addSubview:self.imgView];
                
                //将每一个imageView添加的装载imageView的数组中,将图片保存的系统相册的时候从此数组中找出相应的 imageView 的 image;
                [self.arrimageView addObject:self.imgView];
                
                [_imgView release];
            }
            
            //将拍摄图片作者的名字拼接到图片详细介绍的后面(作者的名字在详细内容后面新起一行显示 '\n')
            ModelForForPhotoDetail *model1 = self.arrForModels[0];
            
            NSString *strForContent = model1.content;
            
            NSString *strForAuthor = model1.author;
            
            self.textView.text = [NSString stringWithFormat:@"%@\n(摄影:%@)", strForContent,strForAuthor];
            
            //显示详细内容
            self.lableForTitle.text = model1.title;
            
            //像是这组图片的总个数和当前显示是第几张图片
            self.lableForPage.text = [NSString stringWithFormat:@"1/%ld", self.arrForModels.count];
            
            
            self.isSelect =  [[DataBaseForPhoto shareDataBaseHandle]select:model1];
            if (self.isSelect)
            {
                [self.buttonForCollect setBackgroundImage:[UIImage imageNamed:@"收藏"] forState:UIControlStateNormal];
            }
            else
            {
                [self.buttonForCollect setBackgroundImage:[UIImage imageNamed:@"取消收藏"] forState:UIControlStateNormal];
            }
            
            self.buttonForSave.enabled = YES;
            
            [self.buttonForSave setBackgroundImage:[UIImage imageNamed:@"授权下载"] forState:UIControlStateNormal];
    }];
}




#pragma mark 创建UIscrollView
- (void)creataScorollView
{
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 300)];
    
    self.scrollView.center = self.view.center;
    
    //开启翻页效果
    self.scrollView.pagingEnabled = YES;
    
    //指定代理人
    self.scrollView.delegate = self;
    
    [self.view addSubview:self.scrollView];
    
    [_scrollView release];
    
    self.scrollView.backgroundColor = [UIColor whiteColor];
    
}





#pragma mark 创建UITextView
- (void)createTextView
{
    self.textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 560, self.view.frame.size.width, self.view.frame.size.height - 610)];
    
    self.textView.backgroundColor = [UIColor clearColor];
    
    self.textView.textColor = [UIColor whiteColor];
    
    [self.view addSubview:self.textView];
    
    self.textView.font = [UIFont systemFontOfSize:22];
    
    //禁止textView的编辑功能;
    self.textView.editable = NO;
    
    [_textView release];
}




#pragma mark 创建标题
- (void)createLableForTitleAndPage
{
    self.lableForTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 530, 300, 30)];
    
    self.lableForPage = [[UILabel alloc] initWithFrame:CGRectMake(300, 530, 114, 30)];
    
    self.lableForTitle.textColor = [UIColor whiteColor];
    
    self.lableForPage.textColor = [UIColor whiteColor];
    
    self.lableForPage.textAlignment = NSTextAlignmentRight;
    
    [self.lableForTitle setFont:[UIFont fontWithName:@"Helvetica-Bold" size:22]];
    
    self.lableForPage.font = [UIFont boldSystemFontOfSize:20];
    
    [self.view addSubview:self.lableForTitle];
    
    [self.view addSubview:self.lableForPage];
    
    [_lableForTitle release];
    
    [_lableForPage release];
}




#pragma mark 添加保存按钮
- (void)addButtonOfSave
{
    self.buttonForSave = [UIButton buttonWithType:UIButtonTypeSystem];
    
    self.buttonForSave.tag = 100;
    
    [self.buttonForSave setBackgroundImage:[UIImage imageNamed:@"禁止下载"] forState:UIControlStateNormal];
    
    self.buttonForSave.frame = CGRectMake(330, self.view.frame.size.height - 50, 40, 40);
    
    self.buttonForSave.enabled = NO;
    
    [self.view addSubview:self.buttonForSave];
    
    
    [self.buttonForSave addTarget:self action:@selector(saveAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    
    self.buttonForCollect = [UIButton buttonWithType:UIButtonTypeSystem];
    
    self.buttonForCollect.tag = 200;
    
    self.buttonForCollect.frame = CGRectMake(90, self.view.frame.size.height - 50, 40, 40);
    
    [self.view addSubview:self.buttonForCollect];
    
    
    [self.buttonForCollect addTarget:self action:@selector(collectAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    self.buttonForShare= [UIButton buttonWithType:UIButtonTypeSystem];
    
    self.buttonForShare.frame = CGRectMake(20, self.view.frame.size.height - 50, 40, 40);
    
    [self.view addSubview:self.buttonForShare];

     [self.buttonForShare setBackgroundImage:[UIImage imageNamed:@"图片分享"] forState:UIControlStateNormal];
    
    [self.buttonForShare addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    


}




#pragma mark 点击Button所触发的方法
- (void)saveAction:(UIButton *)button
{
    
    //根据scrollView的内容偏移量计算出当前的页数
    NSInteger path = (NSInteger)self.scrollView.contentOffset.x / 414;
    
    //根据当前的页数找到在arrimageView数组中对应的imageView;
    UIImageView *imageView = self.arrimageView[path];
    
    //调用UIImageWriteToSavedPhotosAlbum 函数 将图片保存到本地相册
    UIImageWriteToSavedPhotosAlbum(imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}




#pragma mark 点击Button所触发的方法
- (void)collectAction:(UIButton *)button
{
   ModelForForPhotoDetail *model3 = self.arrForModels[self.path];
    
   self.isSelect =  [[DataBaseForPhoto shareDataBaseHandle]select:model3];
    
    if (self.isSelect)
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否取消收藏" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            NSLog(@"3");
            
            ModelForForPhotoDetail *model3 = self.arrForModels[self.path];
            
            [[DataBaseForPhoto shareDataBaseHandle]deleteWithCode:model3.title];
            
            
            [self.buttonForCollect setBackgroundImage:[UIImage imageNamed:@"取消收藏"] forState:UIControlStateNormal];
            
            self.isSelect = NO;
            
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            
            [alert dismissViewControllerAnimated:YES completion:^{
                
                
            }];
            
        }];
        
        [alert addAction:okAction];
        
        [alert addAction:cancelAction];
        
        [self presentViewController:alert animated:YES completion:^{
          
        }];
    }
    else
    {
        
        [[DataBaseForPhoto shareDataBaseHandle] insertCollect:self.arrForModels[self.path]];
        
        [self.buttonForCollect setBackgroundImage:[UIImage imageNamed:@"收藏"] forState:UIControlStateNormal];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:alert animated:YES completion:^{
            
            [alert dismissViewControllerAnimated:YES completion:^{
                
            }];
        }];
        
        self.isSelect = YES;
    }
}




- (void)shareAction:(UIButton *)button
{
    NSLog(@"收藏");
}




#pragma mark UIImageWriteToSavedPhotosAlbum 触发的方法(回馈照片是否保存成功的信息)
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error == nil)
    {
        NSLog(@"保存成功");
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"保存成功" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *actionForOK = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction:actionForOK];
        
        [self presentViewController:alert animated:YES completion:^{
            
        }];
    }
    else
    {
        NSLog(@"保存失败");
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"保存失败" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *actionForOK = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction:actionForOK];
        
        [self presentViewController:alert animated:YES completion:^{
            
        }];
    }
}





#pragma mark UIScrollViewDelegate 的协议方法 >>>>>>
#pragma mark Scroll完成拖动的时候调用此方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //根据scrollView的内容偏移量计算出当前的页数
    self.path  = (NSInteger)self.scrollView.contentOffset.x / 414;
    
    ModelForForPhotoDetail *model = self.arrForModels[self.path];
    
    
    NSString *strForContent = model.content;
    
    NSString *strForAuthor = model.author;
    
    
    self.isSelect =  [[DataBaseForPhoto shareDataBaseHandle]select:model];
    if (self.isSelect)
    {
        [self.buttonForCollect setBackgroundImage:[UIImage imageNamed:@"收藏"] forState:UIControlStateNormal];
    }
    else
    {
        [self.buttonForCollect setBackgroundImage:[UIImage imageNamed:@"取消收藏"] forState:UIControlStateNormal];
    }

    self.textView.text = model.content;
    
    self.textView.text = [NSString stringWithFormat:@"%@\n(摄影:%@)", strForContent,strForAuthor];
    
    self.lableForTitle.text = model.title;
    
    self.lableForPage.text = [NSString stringWithFormat:@"%ld/%ld", self.path + 1, self.arrForModels.count];
}






@end
